package com.acme.clientside;

import com.sun.org.apache.bcel.internal.classfile.ConstantValue;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;

public class ChatClient {

    public static final String EXIT = "<exit>";
    public static final String PATH_CLIENT = "src\\main\\java\\com\\acme\\clientside\\config.properties";
    private ObjectOutputStream out;
    private ObjectInputStream in;

    private Socket loadProperty() throws IOException {
        Properties configFile = readConfig(PATH_CLIENT);
        int port = Integer.parseInt(configFile.getProperty("port"));
        InetAddress ip = InetAddress.getByName(configFile.getProperty("ip"));
        return new Socket(ip, port);
    }

    public void startChat() throws UnknownHostException {
        try (Socket socket = loadProperty();
             ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
            this.out = out;
            this.in = in;
            messaging();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Properties readConfig(String filePath) {
        Properties configClient = null;
        try (FileInputStream inputStream = new FileInputStream(new File(filePath))) {
            configClient = new Properties();
            configClient.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configClient;

    }


    private void messaging() throws IOException, InterruptedException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            ServerConnection serverConnection = new ServerConnection(this.in);
            serverConnection.thread.start();
            String message;
            do {
                message = reader.readLine();
                if (!serverConnection.thread.isAlive())
                    break;
                sendMessage(message);
            } while (!message.equals(EXIT));

            System.out.printf("Disconecting... ");
            serverConnection.thread.join();
            System.out.printf("Disconected!\n");
        }
    }

    private void sendMessage(String message) throws IOException {
        if (this.out == null)
            throw new NullPointerException("OUT is null!");
        if (message == null || message.isEmpty())
            return;
        this.out.writeObject(message);
    }


    public static void main(String[] args) throws UnknownHostException {
        new ChatClient().startChat();
    }

}
